import React,{Component} from 'react'

import {
    View,
    Text,
    Button,
    StyleSheet,
    Alert,
    Image,
    TouchableNativeFeedback,
    Dimensions,
    TextInput,
    ToastAndroid,
    ScrollView,
    Modal,
    FlatList
}from 'react-native'

import loading from '../../commons/loading'

import ImagePicker from 'react-native-image-crop-picker'; 

const { width, height } = Dimensions.get('window');


const styles=StyleSheet.create({
    warp:{
        width:width,
        height:height
    },
    topchoseimg:{
        width:9*width/10,
        height:9*width/10,
        marginLeft:'5%',
        marginTop:10,
        backgroundColor:'white'
    },
    cameraBtn:{
        width:9*width/10,
        height:9*width/10,
        
    },
    toptip:{
        color:'black',
        
    },
    realimg:{
        width:'100%',  
    },
    bottomchosewarp:{
        position:'absolute',
        left:0,
        bottom:0,
        width:width,
        height:height,
        backgroundColor:'rgba(0,0,0,0.3)'
    },
    bottomchose:{
        position:'absolute',
        width:9*width/10,
        bottom:10,
        left:0.5*width/10
    },
    bottomchosetop:{
        borderTopLeftRadius:10,
        borderTopRightRadius:10,
        width:'100%',
        backgroundColor:'white',
        height:50,
        textAlign:'center',
        lineHeight:35,
        color:'black'
    },
    bottomchosemiddle:{
        width:'100%',
        borderBottomLeftRadius:10,
        borderBottomRightRadius:10,
        height:50,
        textAlign:'center',
        lineHeight:35,
        color:'black'
    },
    bottomchosebottom:{
        borderBottomLeftRadius:10,
        borderBottomRightRadius:10,
        borderTopLeftRadius:10,
        borderTopRightRadius:10,
        width:'100%',
        height:50,
        backgroundColor:'white',
        marginTop:10,
        textAlign:'center',
        lineHeight:35
    },
    formadd:{
        width:'100%',
        backgroundColor:'white',
        marginTop:10
    },
    list:{
        width:'100%',
        height:50,
        borderTopWidth:1,
        paddingLeft:10,
        paddingRight:10,
        borderColor:'#ddd',
        flexDirection:'row',
        justifyContent:'space-between',
        alignItems:'center'
    },
    rightinputtext:{
        width:width/2,
        color:"#666",
        fontSize:16,
        borderRadius:4,
    },
    rightHwarp:{
        width:width/2,
        flexDirection:'row',
        justifyContent:'space-around',
        alignItems:'center'
    },
    rightHtext:{
        width:width/5,
    },
    righttext:{
        width:width/2,
        color:"#666",
        fontSize:16,
    },
    lefttext:{
        color:'black'
    }
})



export default class FoodGoodsAdd extends Component {
    static navigationOptions={
        title:'添加菜品',
        headerTitleStyle: {
        alignSelf:'center'
      },
    };

    state = {
            showload:false,
            url:'http://www.dadu999.com/houtai/userfiles/a9c96f956fd1499a9d5c4625c2905e5a/images/seller/foodManage/2017/10/%E9%BA%BB%E8%BE%A3%E8%92%9C%E9%A6%99%E8%B1%86%E8%85%90.jpg',
            showchose:false,
            guige:[{
                name:'请选择',
                price:'10',
                des:"",
                FHmin:'0',
                FHmax:'0',
                SHmin:'0',
                SHmax:'0'
            }
            ],
            guigechosed:[],
            type:'请选择',
            name:'',
            imgdata:'',
            sort:'',
            foodtype:[]
        }
    hidechose=function(){
        this.setState({
            showchose:false
        })
    }

    addguige=function(){
        var data=this.state.guige
        data.push(
            {
                name:'请选择',
                price:'0',
                des:"",
                FHmin:'0',
                FHmax:'0',
                SHmin:'0',
                SHmax:'0'
            }
        )
        this.setState({
            guige:data
        })
    }

    async componentWillMount(){
        if(!global.guige){
            try {

            let response = await fetch(global.mainurl+"bossHelper/getFoodSpecs?sellerid="+global.sellerid+"&userid="+global.userdata.id+"&token="+global.token);
            var data=await response.json()
            if(data.code==1){
                       global.guige=data.data
                    }
            else{
								
						}
            } 
            catch(error) {
                 console.log(error)
                  ToastAndroid.show('网络出错', ToastAndroid.SHORT);
            }
        }

        var ar1=[];
        global.guige.forEach(data=>{
            ar1.push(data.name)
         })
                       

        var arr=[]
        global.foodtype.forEach(function(data){
            arr.push(data.name)
        })
        console.log(ar1)
        this.setState({
            foodtype:arr,
            guigechosed:ar1
        })

        if(this.props.navigation.state.params.old){
            var old=this.props.navigation.state.params.old
            var nowguige=[];
            old.listin.forEach(data=>{
                nowguige.push({
                    name:data.listName,
                    price:data.price.toString(),
                    des:"",
                    FHmin:data.firstGearMin.toString(),
                    FHmax:data.firstGearMax.toString(),
                    SHmin:data.secondGearMin.toString(),
                    SHmax:data.secondGearMin.toString()
                })
            })
            this.setState({
                name:old.listName,
                type:old.name,
                sort:old.sort,
                guige:nowguige,
                url:'http://www.dadu999.com'+old.src
            })
        }
    }
 
    addfood= async function(){
        try{

        var guigedata=[]

        if(this.state.imgdata==''){
             ToastAndroid.show('请选择菜品图片', ToastAndroid.SHORT);
            return
        }

        if(this.state.name==''){
            ToastAndroid.show('请填写菜品名称', ToastAndroid.SHORT);
            return
        }
        if(this.state.sort==''){
            ToastAndroid.show('请填写菜品排序', ToastAndroid.SHORT);
            return
        }

        if(this.state.type=='请选择'){
             ToastAndroid.show('请选择菜品种类', ToastAndroid.SHORT);
            return
        }



        var typeid
         global.foodtype.forEach(data=>{
                if(data.name==this.state.type){
                    typeid=data.id
                }
            })

        for(var i=0;i<this.state.guige.length;i++){
            var item=this.state.guige[i];
            var guigeid
            
            if(item.name==''||item.price==''||item.price==0||item.name=='请选择'){
                 ToastAndroid.show('请填写完整的规格信息', ToastAndroid.SHORT);
                 return
            }
            global.guige.forEach(data=>{
                if(data.name==item.name){
                    
                    guigeid=data.id
                }
            })
           
                guigedata.push({
                    "foodspecsid":guigeid,
					"price":item.price,
					"nowprice":item.price,
					"fooddescriotion":item.des
                })
            
        }
        this.setState({
            showload:true
        })
       var result= await fetch(global.mainurl+'/bossHelper/foodAdd', {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                        },
                        
                        body: JSON.stringify({
                            
			    			"id":this.props.navigation.state.params.old?this.props.navigation.state.params.old.id:'',
			    		    "foodname": this.state.name,
			    		    "sortValue":this.state.sort,
			    		    "foodimage1":this.props.navigation.state.params.old?this.props.navigation.state.params.old.src:'',
			    		    "foodimage2": this.state.imgdata,
			    		    "sellerid": global.sellerid,
			    		    "foodtype": {
			    		        "id": typeid
			    		    },
			    		    "foodInfoList": guigedata,
			    		    "userid":global.userdata.id,
							    "token":global.token
			    	
                        })
                    })
        var result1= await result.json()
        console.log(result1)
        if(result1.code==1){
            ToastAndroid.show('添加成功', ToastAndroid.SHORT);
            this.props.navigation.state.params.reload()
            this.props.navigation.goBack()
        }
        else{
            ToastAndroid.show('添加失败', ToastAndroid.SHORT);
        }
        this.setState({
            showload:false
        })
    }
    
    catch(error){
        console.log(error)
        ToastAndroid.show('添加失败', ToastAndroid.SHORT);
        
    }
    this.setState({
            showload:false
        })
    }

    deleteguige=function(){
        var data=this.state.guige
        if(data.length==1){
            alert("最少要有一个规格")
            return
        }
        data.pop()
        this.setState({
            guige:data
        })
    }

    guigelist=function(){
        var result=''
        
            result=<View style={styles.formadd}>
                <View style={styles.list}>
                    <Text style={styles.lefttext}>规格名称（必填）</Text>
                    <Text style={styles.righttext}>请选择</Text>
                </View>

                <View style={styles.list}>
                    <Text style={styles.lefttext}>价格</Text> 
                    <TextInput 
                    clearButtonMode='always'
                    underlineColorAndroid="transparent"
                    selectionColor="red"
                      style={styles.rightinputtext}/>
                </View>
                
                <View style={styles.list}>
                    <Text style={styles.lefttext}>红包</Text>
                    <TextInput  style={styles.rightinputtext}/>
                </View>

                <View style={styles.list}>
                    <Text style={styles.lefttext}>描述</Text>
                    <TextInput  style={styles.rightinputtext}/>
                </View>
                </View>
        
            
      
            return result
       
    }


    openchose=function(){
        this.setState({
            showchose:true
        })
    }

    onFileUpload=function(file){
         var p = new Promise(function(resolve, reject){
                resolve(1)
        });
        return p;
    }

    changeinput=function(index,text,type){
            var data=this.state.guige
            data[index][type]=text
            this.setState({
                guige:data
            })
        
    }

    picker=function(){
        var _this=this
        ImagePicker.openPicker({  
                width: 800,  
                height: 800,
                includeBase64:true,  
                cropping: true  
                }).then(image => {  
                _this.setState({
                    url:image.path,
                    imgdata:image.data
                });  
                console.log(image)
                _this.hidechose()
            });  
    }

    savedata=function(data){
        this.setState({
            type:data
        })
    }

    camera=function(){
        var _this=this
        ImagePicker.openCamera({  
                width: 800,  
                height: 800,  
                includeBase64:true, 
                cropping: true  
                }).then(image => {  
                _this.setState({
                    url:image.path,
                    imgdata:image.data
                });  
                _this.hidechose()
            });  
    }


    render(){
        return(
            <ScrollView style={styles.warp}>
               {loading(this.state.showload)}
                <View style={styles.topchoseimg}> 
                <TouchableNativeFeedback
                onPress={()=>{this.openchose()}}
                >
                <View style={{width:"100%",height:'100%'}}>
                <Image style={{width:"100%",height:'100%'}} resizeMode="contain" source={{uri:this.state.url}}/>
                </View>       
                </TouchableNativeFeedback>
                </View> 
                

                <View style={styles.formadd}>
                <View style={styles.list}>
                    <Text style={styles.lefttext}>菜品分类（必填）</Text>
                    <Text style={styles.righttext}
                    onPress={()=>{
                        this.props.navigation.navigate("Chose",{data:this.state.foodtype,save:(d)=>{this.savedata(d)}})
                    }}
                    >{this.state.type}</Text>
                </View>

                <View style={styles.list}>
                    <Text style={styles.lefttext}>菜名</Text> 
                    <TextInput 
                    clearButtonMode='always'
                    placeholder="请填写菜品名称"
                    underlineColorAndroid="transparent"
                    defaultValue={this.state.name}
                    selectionColor="red"
                    onChangeText={(text)=>{
                        this.setState({
                            name:text
                        })
                    }}
                      style={styles.rightinputtext}/>
                </View>
                
                <View style={styles.list}>
                    <Text style={styles.lefttext}>菜品排序</Text>
                    <TextInput
                    keyboardType={'numeric'}
                    defaultValue={this.state.sort}
                    placeholder="请填写菜品排序"
                    onChangeText={(text)=>{
                        this.setState({
                            sort:text
                        })
                    }}
                    style={styles.rightinputtext}/>
                </View>
                </View>




                <FlatList
                style={{marginTop:20}}
                keyExtractor={(item1, index2) => index2}
                data={this.state.guige}
                renderItem={(item)=>{
                                return(
                                    <View style={styles.formadd}>
                            <View style={styles.list}>
                                <Text style={styles.lefttext}>规格名称（必填）</Text>
                                <Text style={styles.righttext}
                                onPress={()=>{
                                     this.props.navigation.navigate("Chose",{data:this.state.guigechosed,save:(d)=>{this.changeinput(item.index,d,'name')}})
                                    }}
                                >{item.item.name}</Text>
                            </View>

                            <View style={styles.list}>
                                <Text style={styles.lefttext}>价格</Text> 
                                <TextInput 
                                placeholder="请填写价格"
                                defaultValue={item.item.price}
                                clearButtonMode='always'
                                underlineColorAndroid="transparent"
                                selectionColor="red"
                                onChangeText={(text) =>{this.changeinput(item.index,text,'price')}}
                                style={styles.rightinputtext}/>
                            </View>
                            
                            <View style={styles.list}>
                                <Text style={styles.lefttext}>一档红包</Text>
                                <View style={styles.rightHwarp}>
                                <TextInput
                                defaultValue={item.item.FHmin}
                                onChangeText={(text) =>{this.changeinput(item.index,text,'FHmin')}}
                                style={styles.rightHtext}/>
                                <Text>至</Text>
                                <TextInput
                                defaultValue={item.item.FHmax}
                                onChangeText={(text) =>{this.changeinput(item.index,text,'FHmax')}}
                                style={styles.rightHtext}/>
                                </View>
                            </View>

                            <View style={styles.list}>
                                <Text style={styles.lefttext}>二档红包</Text>
                                <View style={styles.rightHwarp}>
                                <TextInput
                                defaultValue={item.item.SHmin}
                                onChangeText={(text) =>{this.changeinput(item.index,text,'SHmin')}}
                                style={styles.rightHtext}/>
                                <Text>至</Text>
                                <TextInput
                                defaultValue={item.item.SHmax}
                                onChangeText={(text) =>{this.changeinput(item.index,text,'SHmax')}}
                                style={styles.rightHtext}/>
                                </View>
                            </View>

                            <View style={styles.list}>
                                <Text style={styles.lefttext}>描述</Text>
                                <TextInput
                                placeholder="请填写菜品描述"
                                style={styles.rightinputtext}
                                defaultValue={item.item.des}
                                onChangeText={(text) =>{this.changeinput(item.index,text,'des')}}
                                
                                />
                            </View>
                            </View>
                    )
                }}
                />
                <Button
                    style={{padding:20}}
                    onPress={()=>{this.addguige()}}
                    title="增加规格"
                    color="#841584"
                    />

                <Button
                    onPress={()=>{this.deleteguige()}}
                    title="减少规格"
                    style={{padding:20}}
                    color="#841584"
                    />
                <Text style={{height:20}}></Text>
                <Button
                    onPress={()=>{
                        Alert.alert(
                            '确定添加该菜品？',
                            null,
                            [
                            {text: '取消', onPress: () => {}},
                            {text: '确定', onPress: () => this.addfood()},
                            {text: '', onPress: () =>{} },
                            ]
                        )
                    }}
                    title="完成"
                    style={{padding:20}}
                    color="#841584"
                    />
                <Text style={{height:20}}></Text>




                <View style={{width:width,height:height,position:'absolute',left:0,top:0}}>
                {
                this.state.showchose?
                
                <Modal
                        animationType='fade'            // 淡入淡出
                        transparent={true}              // 透明
                        visible={true}    // 根据isModal决定是否显示
                        onRequestClose={() => {console.log("123")}}  // android必须实现
                    >

                <View style={styles.bottomchosewarp}>
                <View style={styles.bottomchose}>
                <Text style={styles.bottomchosetop}
                onPress={()=>{this.camera()}}>
                拍照</Text>
                <Text style={{width:'100%',height:0.5,backgroundColor:'#ddd'}}></Text>
                
                <TouchableNativeFeedback
                background={TouchableNativeFeedback.Ripple('#ddd', false)}
                onPress={()=>{this.picker()}}
                >
                <View style={{width:'100%',height:50,backgroundColor:'white', borderBottomLeftRadius:10,borderBottomRightRadius:10}}>
                <Text style={styles.bottomchosemiddle}>从手机相册选择</Text>
                </View>
                </TouchableNativeFeedback>

                <Text style={styles.bottomchosebottom} onPress={()=>{this.hidechose()}}>取消</Text>
                </View>
                </View>
                </Modal>
                
                :
                <Text></Text>
                }
                </View>
            </ScrollView>
        )
    }


} 